import postRobot from "post-robot";
import { ACTIONS, ActionType } from "../actions";

const LISTENER_MAP = {};

export function registerListener(actionType: ActionType, callBack: () => any) {
  if (!ACTIONS[actionType]) throw new Error("action is not defined");
  const action = ACTIONS[actionType];
  if (LISTENER_MAP[action]) {
    LISTENER_MAP[action].cancel();
  }
  const listener = postRobot.on(
    action,
    {
      domain: window.location.origin,
    },
    callBack
  );
  LISTENER_MAP[action] = listener;
  return listener;
}
